package com.cms.intelligent_control.common

import android.media.MediaPlayer
import android.util.Log
import com.cms.intelligent_control.config.Config
import com.cms.intelligent_control.common.websocket.WebSocketHelper

class TTSHelper {
    private val webSocketHelper by lazy {
        WebSocketHelper(Config.baseWsUrl + "websocketopen/platTTs")
    }
    private val mMediaPlayer by lazy {
        MediaPlayer()
    }

    public fun startTTS(text: String) {
        webSocketHelper.start {
            onOpen {
                webSocketHelper.send(text)
            }
            onMessage {
                Log.e("TTSHelper", it)
                val url = Config.baseFilePrefix + it.substring(it.lastIndexOf("/") + 1)
                playAudio(url)
                webSocketHelper.close()
            }
        }
    }

    private fun playAudio(url: String) {
        try {
            mMediaPlayer.reset()
            mMediaPlayer.setDataSource(url)
            mMediaPlayer.setOnCompletionListener {

            }
            mMediaPlayer.prepare()
            mMediaPlayer.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}